<template>
  <div class="user-manage-container">
    <div class="left-container flex">
      <!-- <a-input-search
        v-model="left.orgName"
        placeholder="请输入组织名称"
        @search="onSearch"
      /> -->
      <!-- 租户名称 -->
      <a-tree-select
        placeholder="请选择租户名称"
        :replaceFields="{
          children: 'child',
          title: 'tenantName',
          key: 'id',
          value: 'tenantCode',
        }"
        v-model="left.proName"
        :tree-data="left.proNameSource"
        @change="tenantChange"
      >
      </a-tree-select>
      <div class="org-tree-data">
        <a-empty v-if="treeData.length == 0" />
        <a-tree
          v-else
          v-model="left.checkedKeys"
          show-icon
          :default-expand-all="true"
          :expanded-keys="left.expandedKeys"
          :auto-expand-parent="left.autoExpandParent"
          :selected-keys="left.selectedKeys"
          :tree-data="treeData"
          :replaceFields="{
            children: 'childs',
            title: 'orgName',
            key: 'id',
          }"
          @expand="onExpand"
          @select="onSelect"
        >
          <template slot="custom" slot-scope="{ childs }">
            <img
              class="menu-icon"
              src="@/assets/images/folder.png"
              v-if="childs"
            />
            <img v-else class="menu-icon" src="@/assets/images/file.png" />
          </template>
        </a-tree>
      </div>
    </div>
    <div class="right-container">
      <!-- 顶部筛选条件 -->
      <div class="conditions-container">
        <ScreenConditions :isDataType="false">
          <template slot="conditions">
            <!-- @change="conditionChange($event, 'status')" -->
            <!-- 用户名称 -->
            <a-input
              v-model.trim="right.userName"
              placeholder="请输入用户名称"
            />
            <!-- 用户状态 -->
            <bjSelect
              :dataResource="right.userStatusSource"
              placeholder="请选择用户状态"
              v-model="right.userState"
              allowClear
              @change="userStatusChange"
            ></bjSelect>
            <!-- 登录账号 -->
            <a-input
              allowClear
              v-model.trim="right.loginId"
              placeholder="请输入登录账号"
            />
            <!-- 手机号码 -->
            <a-input
              allowClear
              type="number"
              v-model.trim="right.mobile"
              placeholder="请输入手机号码"
            />
          </template>
          <template slot="operate">
            <a-button type="primary" @click="getSearch"> 查询 </a-button>
          </template>
        </ScreenConditions>
      </div>
      <!--  -->
      <div class="result-container flex">
        <div class="common-result-container-header" header="用户管理">
          <div>
            <a-button type="primary" @click="gotoAdd" v-if="showButton">
              新增
            </a-button>
            <a-button
              class="solid-line"
              @click="downloadTemplate"
              v-if="showButton"
            >
              下载模板
            </a-button>
            <a-button
              class="solid-line"
              @click="importTemplate"
              v-if="showButton"
            >
              批量导入
            </a-button>
            <input
              accept=".xls,.xlsx"
              @change="excelChange"
              type="file"
              ref="upload"
              id="upload"
              style="display: none"
            />
          </div>
        </div>
        <div class="result-body flex">
          <div class="table-container" v-loading="loading">
            <vxe-table
              align="center"
              :data="tableSource"
              show-overflow
              show-header-overflow
              show-footer-overflow
              show-footer
              :column-config="{ resizable: true }"
              class="scrollbarStyle"
              height="99%"
              :sort-config="{ trigger: 'cell' }"
              ref="xTable"
              :scroll-x="{ gt: 10 }"
              :scroll-y="{ gt: 100 }"
              row-id="id"
              :checkbox-config="{
                reserve: true,
              }"
            >
              <vxe-column
                :title="item.title"
                :field="item.key"
                :key="index"
                :min-width="item.width"
                show-overflow
                v-for="(item, index) in tableColumns"
              >
                <template slot-scope="scope">
                  <div v-if="item.key == 'userState'">
                    <div
                      class="status-text"
                      :class="[checkStatusClass(scope.row)]"
                    >
                      {{ fliterName(scope.row) }}
                    </div>
                  </div>
                  <div v-else-if="item.key == 'isStatus'">
                    {{ fliterMark(scope.row) }}
                  </div>
                  <div v-else>{{ scope.row[item.key] }}</div>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <div class="text-button-group">
                    <a-button
                      type="link"
                      v-if="row.edit && showButton"
                      @click="gotoEdit(row)"
                    >
                      编辑
                    </a-button>
                    <a-button
                      type="link"
                      v-if="row.reset && showButton"
                      @click="reset(row)"
                    >
                      重置
                    </a-button>
                    <a-button
                      type="link"
                      class="danger"
                      v-if="row.del && showButton"
                      @click="handleDelClick(row)"
                    >
                      删除
                    </a-button>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <!-- 分页 -->
          <div class="pager-container">
            <vxe-pager
              background
              :current-page.sync="pager.page"
              :page-size.sync="pager.pageSize"
              :total="pager.total"
              :layouts="[
                'PrevPage',
                'JumpNumber',
                'NextPage',
                'Sizes',
                'FullJump',
              ]"
              @page-change="paginationChange"
            >
              <template #left>
                <div class="vxe-pager-left-tip-container">
                  第<span>1</span>到<span
                    >{{ Math.ceil(pager.total / pager.pageSize) || 1 }}页 </span
                  >共<span>{{ pager.total }}</span
                  >条记录
                </div>
              </template>
            </vxe-pager>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <addModal :visible.sync="addVisible" :model="model"></addModal>
    <!-- 重置 -->
    <resetModal :visible.sync="resetVisible" :model="model"></resetModal>
  </div>
</template>

<script>
//【用户管理】
import bjSelect from "@/components/bj-select";
import {
  addAttributeByKey,
  downLoadFileByArraybuffer,
  notificationTip,
} from "@/utils";
import addModal from "./components/addModal";
import resetModal from "./components/resetModal";
import { getTenantList } from "@/api/user-center/organizationManage.js";
import { getLoginData } from "@/tools";
import {
  getUserTree,
  getUserManageList,
  getUserDelete,
  getUserTemplate,
  getUserImport,
  getPurView,
} from "@/api/user-center/userManage.js";
export default {
  components: {
    bjSelect,
    addModal,
    resetModal,
  },
  data() {
    return {
      left: {
        //租户名称
        proName: undefined,
        proNameSource: [],
        proNameLoading: false,
        //组织名称
        orgName: "",
        checkedKeys: [],
        expandedKeys: [],
        selectedKeys: [],
        autoExpandParent: false,
      },
      treeData: [],
      right: {
        //登录账号
        loginId: "",
        //手机号
        mobile: "",
        //用户名称
        userName: "",
        //用户状态
        userStatusSource: [
          { key: 1, value: "未激活" },
          { key: 2, value: "正常" },
          { key: 3, value: "已注销" },
          { key: 4, value: "密码锁定" },
        ],
        userState: undefined,
      },
      //table
      tableSource: [],
      tableColumns: [
        {
          title: "登录账号",
          dataIndex: "loginId",
          key: "loginId",
          width: "",
        },
        {
          title: "昵称",
          dataIndex: "userName",
          key: "userName",
          width: "",
        },
        {
          title: "手机号",
          dataIndex: "mobile",
          key: "mobile",
          width: "",
        },
        {
          title: "邮箱",
          dataIndex: "email",
          key: "email",
          width: "",
        },
        {
          title: "用户状态",
          dataIndex: "userState",
          key: "userState",
          width: "",
        },
        {
          title: "用户标识",
          dataIndex: "isStatus",
          key: "isStatus",
          width: "",
        },
        {
          title: "最后登录时间",
          dataIndex: "updateTime",
          key: "updateTime",
          width: "",
        },
      ],
      loading: false,
      //分页
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      //新增弹窗
      addVisible: false,
      //重置弹窗
      resetVisible: false,
      //组件传参
      model: {
        id: "",
        orgId: "",
        text: "",
      },
      //按钮权限
      showButton: false,
    };
  },
  mounted() {
    this.getPurviewFlag();
    this.getTenantList();
  },
  methods: {
    //查询操作权限
    getPurviewFlag() {
      getPurView()
        .then((res) => {
          this.showButton = res?.data?.result || false;
        })
        .catch((_) => {
          this.showButton = false;
        });
    },
    //【查询条件】查询项目名称
    getTenantList() {
      this.left.proNameLoading = true;
      return new Promise((resolve, reject) => {
        let { userId } = getLoginData();
        getTenantList({ userId })
          .then((res) => {
            let { data } = res;
            let tree = data?.result || [];
            this.left.proNameSource = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              tree,
              "child"
            );
            let { tenantCode = "" } = JSON.parse(
              localStorage.getItem("ORGANIZATION") || "{}"
            );
            this.left.proName = tenantCode;
            this.getUserManageTree();
            resolve();
          })
          .catch((_) => {
            this.left.proName = undefined;
            this.left.proNameSource = [];
            reject();
          })
          .finally((_) => {
            this.left.proNameLoading = false;
          });
      });
    },
    //选择租户
    tenantChange() {
      this.getUserManageTree();
    },
    //查询用户树
    getUserManageTree() {
      let { orgName, proName } = this.left;
      return new Promise((resolve, reject) => {
        getUserTree({ orgName, tenantCode: proName })
          .then((res) => {
            let { data } = res;
            this.treeData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              data?.result || [],
              "childs"
            );
            this.left.expandedKeys = [this.treeData?.[0].id];
            this.left.selectedKeys = [this.treeData?.[0].id];
            this.model.orgId = this.treeData?.[0].id;
            this.getTableData();
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          });
      });
    },
    //组织名称搜索
    onSearch() {
      this.getUserManageTree();
    },
    //树展开事件
    onExpand(expandedKeys) {
      this.left.expandedKeys = expandedKeys;
      this.left.autoExpandParent = false;
    },
    //树选择事件
    onSelect(selectedKeys, el) {
      let { id } = el.node.dataRef;
      this.left.selectedKeys = [id];
      this.model.orgId = id;
      this.getSearch();
    },
    //查询列表
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { userName, userState, loginId, mobile } = this.right;
      let { orgId } = this.model;
      return new Promise((resolve, reject) => {
        getUserManageList({
          page,
          pageSize,
          userName,
          userState: this.filterkey(userState),
          orgId,
          loginId,
          mobile,
        })
          .then((res) => {
            let {
              data: { result },
            } = res;
            this.tableSource = result?.rows || [];
            this.pager.total = result?.total || 0;
            resolve();
          })
          .catch((_) => {
            this.tableSource = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
    //新增
    gotoAdd() {
      this.model.text = "新增";
      this.model.id = "";
      if (this.model.orgId) {
        this.addVisible = true;
      } else {
        this.$message.warning("请选择用户所属组织");
      }
    },
    //编辑
    gotoEdit(row) {
      this.model.text = "编辑";
      this.model.id = row.id;
      this.addVisible = true;
    },
    //删除
    handleDelClick(row) {
      let that = this;
      let dataLength = that.tableSource.length;
      let { id } = row;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定删除所选内容?",
        content: "删除内容后,将无法恢复。",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          getUserDelete(id)
            .then((res) => {
              if (dataLength == 1 && that.pager.page > 1) {
                that.pager.page -= 1;
              }
              notificationTip("success", "用户删除成功！");
              that.getTableData();
            })
            .catch();
        },
        onCancel() {},
      });
    },
    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    //下载模板
    downloadTemplate() {
      let { proName } = this.left;
      getUserTemplate(proName).then((data) => {
        downLoadFileByArraybuffer(data, "用户管理模板");
      });
    },
    //模板导入
    importTemplate() {
      this.$refs.upload.click();
    },
    excelChange(event) {
      let { proName } = this.left;
      let file = event.target.files[0];
      let formdata = new FormData();
      formdata.append("uploadFile", file);
      getUserImport(formdata, proName)
        .then((res) => {
          event.target.value = "";
          let { data } = res;
          let errorMsg = data?.result?.errorMsg || [];
          let success = data?.result?.success || 0;
          notificationTip("success", "用户管理模板" + success + "条导入成功");
          if (errorMsg.length != 0) {
            let msg = errorMsg.join("");
            notificationTip("warning", msg || "请检查必填项是否填写完整!");
          }
          this.getTableData();
        })
        .catch((err) => {
          event.target.value = "";
        });
    },
    //重置
    reset(row) {
      this.resetVisible = true;
      this.model.id = row.id;
      this.model.text = row.userName;
    },
    //查询
    getSearch() {
      this.pager.page = 1;
      this.getTableData();
    },
    userStatusChange(ev) {
      this.right.userState = ev;
      this.getSearch();
    },
    filterkey(data = undefined) {
      return data ? data.key : "";
    },
    //校验状态名称
    fliterName(row) {
      let { userState } = row;
      switch (userState) {
        case 1:
          return "未激活";

        case 2:
          return "正常";

        case 3:
          return "已注销";

        case 4:
          return "密码锁定";

        default:
          return "--";
      }
    },

    //校验状态className
    checkStatusClass(row) {
      let { userState } = row;
      switch (userState) {
        case 1:
          return "no-activate";

        case 2:
          return "normal";

        case 3:
          return "cancel";

        case 4:
          return "lock";

        default:
          return "cancel";
      }
    },
    //校验用户标识
    fliterMark(row) {
      let { isStatus } = row;
      switch (isStatus) {
        case "0":
          return "超级管理员";

        case "1":
          return "普通用户";

        default:
          return "--";
      }
    },
  },
};
</script>

<style lang="less">
.user-manage-container {
  height: 100%;
  .flex();
  box-sizing: border-box;
  padding: 0px 0px 10px 10px;
  overflow: hidden;
  .left-container {
    height: 100%;
    width: 300px;
    flex-shrink: 0;
    border-right: 1px solid #ededed;
    background: #fff;
    padding: 10px 20px;
    box-sizing: border-box;
    flex-direction: column;
    overflow: hidden;
    .org-tree-data {
      flex: 1;
      padding: 20px 0;
      .custom-scrollbar();
      .ant-tree {
        li {
          width: 100%;
          .ant-tree-node-content-wrapper {
            width: calc(100% - 40px);
          }
        }
      }
    }
  }
  .right-container {
    flex: 1;
    height: 100%;
    .flex();
    background: #fff;
    box-sizing: border-box;
    flex-direction: column;
    .result-container {
      flex-direction: column;
      flex: 1;
      .common-result-container-header {
        padding: 10px 20px 20px 20px;
        flex-shrink: 0;
      }
      .result-body {
        flex: 1;
        .flex();
        flex-direction: column;
        .table-container {
          flex: 1;
          .status-text {
            border-radius: 4px;
            color: #fff;
            width: 68px;
            .flex();
            align-items: center;
            justify-content: center;
            margin: 0 auto;
            font-size: 12px;
            &.normal {
              background: #4bc964;
            }
            &.lock {
              background: #ff3f4a;
            }
            &.cancel {
              background: #f1f2f7;
              color: #aab0bc;
            }
            &.no-activate {
              background: #0098ff;
            }
          }
          .vxe-table--render-default {
            .vxe-table--border-line {
              border-left: none;
              border-right: none;
            }
          }
        }
        .pager-container {
          flex-shrink: 0;
        }
      }
    }
  }
}
</style>
